package com.cuit.limit;


import com.cuit.enums.RpcErrorMessageEnum;
import com.cuit.exception.RpcException;
import com.cuit.remoting.dto.RpcRequest;
import com.sun.tools.javac.comp.Flow;
import javafx.util.Pair;
import lombok.Data;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class ServiceFlowManager {

    private final Map<String, FlowController> serviceFlowController = new ConcurrentHashMap<>();

    public void callServiceFlow(RpcRequest rpcRequest)throws Exception{
        if (rpcRequest.getMaxCount() <= 0){
            throw new RpcException(RpcErrorMessageEnum.MAXCOUNT_CAN_NOT_LE_ZERO);
        }
        FlowController flowController = serviceFlowController.get(rpcRequest.getRpcServiceName());
        if (flowController == null){
            flowController = new FlowController();
            serviceFlowController.put(rpcRequest.getRpcServiceName(), flowController);
        }
        flowController.incrementAtCurrentMinute();
    }



    public boolean isAllow(RpcRequest rpcRequest){
        Long maxCount = rpcRequest.getMaxCount();
        if (maxCount <= 0){
            throw new RpcException(RpcErrorMessageEnum.MAXCOUNT_CAN_NOT_LE_ZERO);
        }
        Long currentCount = serviceFlowController.get(rpcRequest.getRpcServiceName()).getCurrentCallCount();

        return currentCount > maxCount ? false : true;
    }

    public void clearNextMinuteCallCount(){
        Set<Map.Entry<String, FlowController>> entries = serviceFlowController.entrySet();
        for (Map.Entry<String, FlowController> entry : entries){
            FlowController flowController = entry.getValue();
            flowController.clearNextMinuteCallCount();
        }
    }
}
